<template>
	<view class="category-container">
		<!-- 自定义导航栏 -->
		<custom-navbar :title="currentCategoryName" :showSearch="true" @search="onSearch"></custom-navbar>

		<!-- 内容区域包装器 -->
		<view class="content-wrapper"
			:style="{ paddingTop: statusBarHeight + navBarHeight + 'px', boxSizing: 'border-box' }">
			<!-- 左侧分类列表 -->
			<scroll-view scroll-y class="category-menu">
				<!-- 固定的三个特殊分类 -->
				<view class="menu-item" :class="{ active: currentCategory === 'core' }" @click="switchCategory('core')">
					<text>定子</text>
				</view>
				<view class="menu-item" :class="{ active: currentCategory === 'shaft' }"
					@click="switchCategory('shaft')">
					<text>转子</text>
				</view>
				<view class="menu-item" :class="{ active: currentCategory === 'parts' }"
					@click="switchCategory('parts')">
					<text>配件</text>
				</view>

				<!-- 动态加载的其他分类 -->
				<view class="menu-item" v-for="(item, index) in categoryList" :key="index"
					:class="{ active: currentCategory == item.id }" @click="switchCategory(item.id)">
					<text>{{ item.categoryName }}</text>
				</view>
			</scroll-view>

			<!-- 右侧商品列表 -->
			<scroll-view scroll-y class="goods-list" @scrolltolower="loadMore">
				<!-- 商品列表 -->
				<view class="goods-container">
					<view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="goToDetail(item)">
						<u-image width="160rpx" height="160rpx" :src="getImageUrl(item.goodsImage)"></u-image>
						<view class="goods-info">
							<text class="goods-name u-line-2">{{ item.goodsSpec || item.goodsName }}</text>
							<text class="goods-price">¥{{ item.retailPrice }}</text>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view class="loading-more" v-if="loading">
					<u-loading></u-loading>
					<text>加载中...</text>
				</view>

				<!-- 无数据提示 -->
				<view class="empty-tip" v-if="goodsList.length === 0 && !loading">
					<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png" text="暂无商品"></u-empty>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import {
		url
	} from '@/constant/domain'

	export default {
		data() {
			return {
				categoryList: [], // 分类列表
				currentCategory: 'core', // 当前选中的分类ID
				currentCategoryName: '定子', // 当前选中的分类名称
				goodsList: [], // 商品列表
				loading: false, // 是否正在加载
				pageNum: 1, // 当前页码
				pageSize: 10, // 每页数量
				hasMore: true, // 是否有更多数据
				specialCategories: {
					'core': '定子',
					'shaft': '转子',
					'parts': '配件'
				},
				statusBarHeight: 20,
				navBarHeight: 44
			}
		},
		created() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;

			if (systemInfo.platform === 'android') {
				this.navBarHeight = 48;
			} else {
				this.navBarHeight = 44;
			}
		},
		onLoad(options) {
			// 如果有传入分类参数，则切换到对应分类
			if (options.category) {
				this.currentCategory = options.category;
				this.currentCategoryName = this.specialCategories[options.category] || options.categoryName || '商品分类';
			}

			// 获取分类列表
			this.getCategoryList();

			// 获取商品列表
			this.getGoodsList(true);
		},
		methods: {
			// 获取分类列表
			getCategoryList() {
				this.$api.getCategoryList().then(res => {
					console.log('分类列表:', res);
					this.categoryList = res || [];
				}).catch(err => {
					console.error('获取分类列表失败:', err);
					uni.showToast({
						title: '获取分类失败',
						icon: 'none'
					});
				});
			},

			// 切换分类
			switchCategory(categoryId) {
				console.log('切换分类:', this.currentCategory, categoryId);
				if (this.currentCategory === categoryId) return;

				this.currentCategory = categoryId;

				// 设置分类名称
				if (this.specialCategories[categoryId]) {
					this.currentCategoryName = this.specialCategories[categoryId];
				} else {
					// 从分类列表中查找对应的分类名称
					const category = this.categoryList.find(item => item.id === categoryId);
					this.currentCategoryName = category ? category.categoryName : '商品分类';
				}

				// 重置分页参数
				this.pageNum = 1;
				this.hasMore = true;

				// 获取商品列表
				this.getGoodsList(true);
			},

			// 获取商品列表
			getGoodsList(refresh = false) {
				if (this.loading || (!this.hasMore && !refresh)) return;

				this.loading = true;

				// 构建查询参数
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize
				};

				// 根据不同分类调用不同的API
				let apiMethod;

				switch (this.currentCategory) {
					case 'core':
						apiMethod = this.$api.listCore(params);
						break;
					case 'shaft':
						apiMethod = this.$api.listShaftspecifications(params);
						break;
					case 'parts':
						apiMethod = this.$api.listParts(params);
						break;
					default:
						// 其他分类，使用通用商品列表API
						params.categoryId = this.currentCategory;
						apiMethod = this.$api.getGoodsList(params);
				}

				apiMethod.then(res => {
					this.loading = false;

					if (refresh) {
						this.goodsList = [];
					}

					if (res && Array.isArray(res)) {
						// 如果返回的是数组，直接使用
						this.goodsList = refresh ? res : [...this.goodsList, ...res];
						this.hasMore = res.length === this.pageSize;
					} else if (res && res.rows && Array.isArray(res.rows)) {
						// 如果返回的是分页对象，取rows属性
						this.goodsList = refresh ? res.rows : [...this.goodsList, ...res.rows];
						this.hasMore = res.rows.length === this.pageSize;
					} else {
						this.hasMore = false;
					}

					// 更新页码
					if (this.hasMore) {
						this.pageNum++;
					}
				}).catch(err => {
					this.loading = false;
					console.error('获取商品列表失败:', err);
					uni.showToast({
						title: '获取商品失败',
						icon: 'none'
					});
				});
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.getGoodsList();
				}
			},

			// 跳转到商品详情
			goToDetail(item) {
				uni.navigateTo({
					url: `/subPack/product/detail?id=${item.id || item.goodsId}`
				});
			},

			// 获取图片URL
			getImageUrl(imagePath) {
				if (!imagePath) return '/static/product/product1.jpg';

				// 如果已经是完整URL，直接返回
				if (imagePath.startsWith('http')) {
					return imagePath;
				}

				// 确保路径以/开头
				if (!imagePath.startsWith('/')) {
					imagePath = '/' + imagePath;
				}

				return url + imagePath;
			},

			// 搜索回调
			onSearch(keyword) {
				if (!keyword) return;
				uni.navigateTo({
					url: `/subPack/search/search?keyword=${encodeURIComponent(keyword)}`
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.category-container {
		display: flex;
		flex-direction: column; // 改为纵向排列
		height: 100vh;
		background-color: #f8f8f8;

		// 内容区域容器
		.content-wrapper {
			display: flex;
			flex: 1;
			width: 100%;
			height: calc(100vh - var(--window-top)); // 减去导航栏高度

			.category-menu {
				width: 180rpx;
				height: 100%;
				background-color: #f5f5f5;

				.menu-item {
					height: 100rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 28rpx;
					color: #333;
					position: relative;

					&.active {
						background-color: #ffffff;
						color: #2979ff;
						font-weight: bold;

						&::before {
							content: '';
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
							width: 6rpx;
							height: 36rpx;
							background-color: #2979ff;
						}
					}
				}
			}

			.goods-list {
				flex: 1;
				height: 100%;
				background-color: #ffffff;

				.goods-container {
					padding: 20rpx;

					.goods-item {
						display: flex;
						padding: 20rpx;
						border-bottom: 1rpx solid #f5f5f5;

						.goods-info {
							flex: 1;
							margin-left: 20rpx;
							display: flex;
							flex-direction: column;
							justify-content: space-between;

							.goods-name {
								font-size: 28rpx;
								color: #333;
								margin-bottom: 10rpx;
								overflow: hidden;
								text-overflow: ellipsis;
								display: -webkit-box;
								-webkit-line-clamp: 2;
								-webkit-box-orient: vertical;
							}

							.goods-price {
								font-size: 32rpx;
								color: #fa3534;
								font-weight: bold;
							}
						}
					}
				}

				.loading-more {
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 20rpx 0;

					text {
						font-size: 24rpx;
						color: #999;
						margin-left: 10rpx;
					}
				}

				.empty-tip {
					padding: 100rpx 0;
				}
			}
		}
	}
</style>